/*
 * Using Ajax to change password
 */
if (typeof HCM !== 'object') var HCM = {};

HCM.changePassword = function(el) {
    var $root_el = $(el);
    var change_button = null;
    var newpassword_input;
    var oldpassword_input;
    var confirmpassword_input;
    var oldpassword_container;
    var newpassword_container;
    var confirmpassword_container;

    this.onReady = function() {
        change_button = $root_el.find('a.ajaxLink');
        oldpassword_container = $root_el.find('span.oldPassword');
        newpassword_container = $root_el.find('span.newPassword');
        confirmpassword_container = $root_el.find('span.confirmPassword');
        newpassword_input = $root_el.find("input[name='newpassword']");
        oldpassword_input = $root_el.find("input[name='oldpassword']");
        confirmpassword_input = $root_el.find("input[name='confirmPassword']");

        change_button.click(function(){
            if (change_button.html() != 'Submit') {
                oldpassword_container.show();
                newpassword_container.show();
                confirmpassword_container.show();
                change_button.html('Submit');
            } else {
                if (validatePassword()) {
                    $root_el.find('p.error').hide();
                    $.post('/change/password',
                    {
                        newpassword: newpassword_input.val(),
                        oldpassword: oldpassword_input.val()
                    }, changePasswordSuccess, 'text');
                } else {
                    $root_el.find('p.error').show();
                }
            }
            
            return;
        });
    };

    var validatePassword = function() {
        if ($.trim(confirmpassword_input.val()) == '' || 
            $.trim(newpassword_input.val()) == '') {
            return false;
        } else if (confirmpassword_input.val() != newpassword_input.val()) {
            return false;
        } else if (confirmpassword_input.val().length < 6) {
            return false;
        }

        return true
    };


    var changePasswordSuccess = function(data) {
        oldpassword_container.hide();
        newpassword_container.hide();
        confirmpassword_container.hide();
        change_button.html('Change password');
    };
}

$(function() {
    $('.profileForm .password').each(function () {
        new HCM.changePassword(this).onReady();
    });
});